//
//  UITextView-Extension.swift
//  表情键盘
//
//  Created by 耐克了解了 on 13/4/17.
//  Copyright © 2017年 耐克了解了. All rights reserved.
//

import UIKit

extension UITextView{
    //获取textView属性字符串，对应的表情字符串
    func getRmoticonString() -> String {
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        
        let range = NSRange(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            //  print(dict)
            //            print(range)NSTextAttachment
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment{
                attrMStr.replaceCharacters(in: range, with: attachment.chs!)
            }
            
        }
        //获取字符串
        return attrMStr.string
        
    }
 
    
    
    func insertEmoticon(emoticon : Emoticon)  {
        //点击的是空白表情
        if  emoticon.isEmpty {
            return
        }
        //删除按钮
        if emoticon.isRemove {
            
            deleteBackward()
            return
        }
        
        // emoji表情
        if emoticon.emoticonCode != nil {
            //获取光标所在位置
            let textReange = selectedTextRange!
            
            //替换emoji表情
            replace(textReange, withText: emoticon.emoticonCode!)
            return
        }
        
        //替换表情:图文混排
        //根据图片路径创建属性字符串
        let attchment = EmoticonAttachment()
        attchment.chs = emoticon.chs
        attchment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        let font = self.font
        attchment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!)
        
        let attrImage = NSAttributedString(attachment: attchment)
        
        //创建可变的属性字符串
        let attrMstr = NSMutableAttributedString(attributedString: attributedText)
        
        //将图片属性字符串替换到可变属性字符串的某一个位置
        let range = selectedRange
        
        attrMstr.replaceCharacters(in: range, with: attrImage)
        
        attributedText = attrMstr
        
        //将文字大小重置
        self.font = font
        
        //将光标设置回原来位置 + 1
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}
